﻿using Lion.WeiXin.Core.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace Lion.WeiXin.Core.Data
{
   public class WeChatUserDAO:IWeChatUser
    {
        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(int AID)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from T_WeChat_User");
            strSql.Append(" where AID=@AID");
            SqlParameter[] parameters = {
					new SqlParameter("@AID", SqlDbType.Int,4)
			};
            parameters[0].Value = AID;

            return SqlHelper.Exists(strSql.ToString(), parameters);
        }

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(string openId)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from T_WeChat_User");
            strSql.Append(" where OpenId=@OpenId");
            SqlParameter[] parameters = {
					new SqlParameter("@OpenId", SqlDbType.VarChar,100)
			};
            parameters[0].Value = openId;

            return SqlHelper.Exists(strSql.ToString(), parameters);
        }


        /// <summary>
        /// 增加一条数据
        /// </summary>
        public int Add(Models.WeChatUserModel model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into T_WeChat_User(");
            strSql.Append("OpenId,NickName,Dic_UserGroup,HeadPicture,VipCardCode,Sex,IsSubscribe,Subscribe_Date,City,Province,Country)");
            strSql.Append(" values (");
            strSql.Append("@OpenId,@NickName,@Dic_UserGroup,@HeadPicture,@VipCardCode,@Sex,@IsSubscribe,@Subscribe_Date,@City,@Province,@Country)");
            strSql.Append(";select @@IDENTITY");
            SqlParameter[] parameters = {
					new SqlParameter("@OpenId", SqlDbType.VarChar,100),
					new SqlParameter("@NickName", SqlDbType.VarChar,50),
					new SqlParameter("@Dic_UserGroup", SqlDbType.Int,4),
					new SqlParameter("@HeadPicture", SqlDbType.VarChar,255),
					new SqlParameter("@VipCardCode", SqlDbType.VarChar,50),
					new SqlParameter("@Sex", SqlDbType.Int,4),
					new SqlParameter("@IsSubscribe", SqlDbType.Int,4),
					new SqlParameter("@Subscribe_Date", SqlDbType.DateTime),
					new SqlParameter("@City", SqlDbType.VarChar,50),
					new SqlParameter("@Province", SqlDbType.NChar,50),
					new SqlParameter("@Country", SqlDbType.NChar,50)};
            parameters[0].Value = model.OpenId;
            parameters[1].Value = model.NickName;
            parameters[2].Value = model.Dic_UserGroup;
            parameters[3].Value = model.HeadPicture;
            parameters[4].Value = model.VipCardCode;
            parameters[5].Value = model.Sex;
            parameters[6].Value = model.IsSubscribe;
            parameters[7].Value = model.Subscribe_Date;
            parameters[8].Value = model.City;
            parameters[9].Value = model.Province;
            parameters[10].Value = model.Country;

            object obj = SqlHelper.GetSingle(strSql.ToString(), parameters);
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(Models.WeChatUserModel model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update T_WeChat_User set ");
            strSql.Append("OpenId=@OpenId,");
            strSql.Append("NickName=@NickName,");
            strSql.Append("Dic_UserGroup=@Dic_UserGroup,");
            strSql.Append("HeadPicture=@HeadPicture,");
            strSql.Append("VipCardCode=@VipCardCode,");
            strSql.Append("Sex=@Sex,");
            strSql.Append("IsSubscribe=@IsSubscribe,");
            strSql.Append("Subscribe_Date=@Subscribe_Date,");
            strSql.Append("City=@City,");
            strSql.Append("Province=@Province,");
            strSql.Append("Country=@Country");
            strSql.Append(" where AID=@AID");
            SqlParameter[] parameters = {
					new SqlParameter("@OpenId", SqlDbType.VarChar,100),
					new SqlParameter("@NickName", SqlDbType.VarChar,50),
					new SqlParameter("@Dic_UserGroup", SqlDbType.Int,4),
					new SqlParameter("@HeadPicture", SqlDbType.VarChar,255),
					new SqlParameter("@VipCardCode", SqlDbType.VarChar,50),
					new SqlParameter("@Sex", SqlDbType.Int,4),
					new SqlParameter("@IsSubscribe", SqlDbType.Int,4),
					new SqlParameter("@Subscribe_Date", SqlDbType.DateTime),
					new SqlParameter("@City", SqlDbType.VarChar,50),
					new SqlParameter("@Province", SqlDbType.NChar,50),
					new SqlParameter("@Country", SqlDbType.NChar,50),
					new SqlParameter("@AID", SqlDbType.Int,4)};
            parameters[0].Value = model.OpenId;
            parameters[1].Value = model.NickName;
            parameters[2].Value = model.Dic_UserGroup;
            parameters[3].Value = model.HeadPicture;
            parameters[4].Value = model.VipCardCode;
            parameters[5].Value = model.Sex;
            parameters[6].Value = model.IsSubscribe;
            parameters[7].Value = model.Subscribe_Date;
            parameters[8].Value = model.City;
            parameters[9].Value = model.Province;
            parameters[10].Value = model.Country;
            parameters[11].Value = model.AID;

            int rows = SqlHelper.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(int AID)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from T_WeChat_User ");
            strSql.Append(" where AID=@AID");
            SqlParameter[] parameters = {
					new SqlParameter("@AID", SqlDbType.Int,4)
			};
            parameters[0].Value = AID;

            int rows = SqlHelper.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool DeleteUser(string openId)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from T_WeChat_User ");
            strSql.Append(" where OpenId=@OpenId");
            SqlParameter[] parameters = {
					new SqlParameter("@OpenId", SqlDbType.VarChar,50)
			};
            parameters[0].Value = openId;

            int rows = SqlHelper.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 批量删除数据
        /// </summary>
        public bool DeleteList(string AIDlist)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from T_WeChat_User ");
            strSql.Append(" where AID in (" + AIDlist + ")  ");
            int rows = SqlHelper.ExecuteSql(strSql.ToString());
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Models.WeChatUserModel GetModel(int AID)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("select  top 1 AID,OpenId,NickName,Dic_UserGroup,HeadPicture,VipCardCode,Sex,IsSubscribe,Subscribe_Date,City,Province,Country from T_WeChat_User ");
            strSql.Append(" where AID=@AID");
            SqlParameter[] parameters = {
					new SqlParameter("@AID", SqlDbType.Int,4)
			};
            parameters[0].Value = AID;

            Models.WeChatUserModel model = new Models.WeChatUserModel();
            DataSet ds = SqlHelper.Query(strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return ConvertToModel(ds.Tables[0].Rows[0]);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Models.WeChatUserModel GetModel(string openId)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("select  top 1 AID,OpenId,NickName,Dic_UserGroup,HeadPicture,VipCardCode,Sex,IsSubscribe,Subscribe_Date,City,Province,Country from T_WeChat_User ");
            strSql.Append(" where OpenId=@OpenId");
            SqlParameter[] parameters = {
					new SqlParameter("@OpenId", SqlDbType.VarChar,100)
			};
            parameters[0].Value = openId;

            Models.WeChatUserModel model = new Models.WeChatUserModel();
            DataSet ds = SqlHelper.Query(strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return ConvertToModel(ds.Tables[0].Rows[0]);
            }
            else
            {
                return new WeChatUserModel();
            }
        }


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Models.WeChatUserModel ConvertToModel(DataRow row)
        {
            Models.WeChatUserModel model = new Models.WeChatUserModel();
            if (row != null)
            {
                if (row["AID"] != null && row["AID"].ToString() != "")
                {
                    model.AID = int.Parse(row["AID"].ToString());
                }
                if (row["OpenId"] != null)
                {
                    model.OpenId = row["OpenId"].ToString();
                }
                if (row["NickName"] != null)
                {
                    model.NickName = row["NickName"].ToString();
                }
                if (row["Dic_UserGroup"] != null && row["Dic_UserGroup"].ToString() != "")
                {
                    model.Dic_UserGroup = int.Parse(row["Dic_UserGroup"].ToString());
                }
                if (row["HeadPicture"] != null)
                {
                    model.HeadPicture = row["HeadPicture"].ToString();
                }
                if (row["VipCardCode"] != null)
                {
                    model.VipCardCode = row["VipCardCode"].ToString();
                }
                if (row["Sex"] != null && row["Sex"].ToString() != "")
                {
                    model.Sex = int.Parse(row["Sex"].ToString());
                }
                if (row["IsSubscribe"] != null && row["IsSubscribe"].ToString() != "")
                {
                    model.IsSubscribe = int.Parse(row["IsSubscribe"].ToString());
                }
                if (row["Subscribe_Date"] != null && row["Subscribe_Date"].ToString() != "")
                {
                    model.Subscribe_Date = DateTime.Parse(row["Subscribe_Date"].ToString());
                }
                if (row["City"] != null)
                {
                    model.City = row["City"].ToString();
                }
                if (row["Province"] != null)
                {
                    model.Province = row["Province"].ToString();
                }
                if (row["Country"] != null)
                {
                    model.Country = row["Country"].ToString();
                }
            }
            return model;
        }

        protected List<Models.WeChatUserModel> ConvertToList(DataSet ds)
        {
            List<Models.WeChatUserModel> list = new List<Models.WeChatUserModel>();
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                Models.WeChatUserModel model = ConvertToModel(row);
                list.Add(model);
            }
            return list;
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<Models.WeChatUserModel> GetUserList(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select AID,OpenId,NickName,Dic_UserGroup,HeadPicture,VipCardCode");
            strSql.Append(" FROM T_WeChat_User inner join T_Dictionary ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            DataSet ds = SqlHelper.Query(strSql.ToString());
            return ConvertToList(ds);
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<Models.WeChatUserModel> GetList(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select AID,OpenId,NickName,Dic_UserGroup,HeadPicture,VipCardCode,Sex,IsSubscribe,Subscribe_Date,City,Province,Country ");
            strSql.Append(" FROM T_WeChat_User ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            DataSet ds = SqlHelper.Query(strSql.ToString());
            return ConvertToList(ds);
        }

        /// <summary>
        /// 获得前几行数据
        /// </summary>
        public List<Models.WeChatUserModel> GetList(int Top, string strWhere, string filedOrder)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select ");
            if (Top > 0)
            {
                strSql.Append(" top " + Top.ToString());
            }
            strSql.Append(" AID,OpenId,NickName,Dic_UserGroup,HeadPicture,VipCardCode,Sex,IsSubscribe,Subscribe_Date,City,Province,Country ");
            strSql.Append(" FROM T_WeChat_User ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            strSql.Append(" order by " + filedOrder);
            DataSet ds = SqlHelper.Query(strSql.ToString());
            return ConvertToList(ds);
        }

        /// <summary>
        /// 获取记录总数
        /// </summary>
        public int GetRecordCount(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) FROM T_WeChat_User ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            object obj = SqlHelper.GetSingle(strSql.ToString());
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        public List<Models.WeChatUserModel> GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("SELECT * FROM ( ");
            strSql.Append(" SELECT ROW_NUMBER() OVER (");
            if (!string.IsNullOrEmpty(orderby.Trim()))
            {
                strSql.Append("order by T." + orderby);
            }
            else
            {
                strSql.Append("order by T.AID desc");
            }
            strSql.Append(")AS Row, T.*  from T_WeChat_User T ");
            if (!string.IsNullOrEmpty(strWhere.Trim()))
            {
                strSql.Append(" WHERE " + strWhere);
            }
            strSql.Append(" ) TT");
            strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
            DataSet ds = SqlHelper.Query(strSql.ToString());
            return ConvertToList(ds);
        }

        /*
        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        public DataSet GetList(int PageSize,int PageIndex,string strWhere)
        {
            SqlParameter[] parameters = {
                    new SqlParameter("@tblName", SqlDbType.VarChar, 255),
                    new SqlParameter("@fldName", SqlDbType.VarChar, 255),
                    new SqlParameter("@PageSize", SqlDbType.Int),
                    new SqlParameter("@PageIndex", SqlDbType.Int),
                    new SqlParameter("@IsReCount", SqlDbType.Bit),
                    new SqlParameter("@OrderType", SqlDbType.Bit),
                    new SqlParameter("@strWhere", SqlDbType.VarChar,1000),
                    };
            parameters[0].Value = "T_WeChat_User";
            parameters[1].Value = "AID";
            parameters[2].Value = PageSize;
            parameters[3].Value = PageIndex;
            parameters[4].Value = 0;
            parameters[5].Value = 0;
            parameters[6].Value = strWhere;	
            return SqlHelper.RunProcedure("UP_GetRecordByPage",parameters,"ds");
        }*/


        /// <summary>
        /// 将 <see cref="DataTable"/> 的数据批量插入到数据库中。
        /// </summary>
        /// <param name="dataTable">要批量插入的 <see cref="DataTable"/>。</param>
        /// <param name="batchSize">每批次写入的数据量。</param>
        public void Insert(List<WeChatUserModel> localUsers, int batchSize = 10000)
        {
            //获取表结构
            DataTable table = SqlHelper.Query("select top 1 * from T_WeChat_User where AID=0").Tables[0];
            table.Clear();

            table.TableName = "T_WeChat_User";

            //加入数据
            foreach (WeChatUserModel wxUser in localUsers)
            {
                DataRow row= table.NewRow();
                row["AID"] = wxUser.AID;
                row["OpenId"] = wxUser.OpenId;
                row["NickName"] = wxUser.NickName;
                row["Dic_UserGroup"] = wxUser.Dic_UserGroup;
                row["HeadPicture"] = wxUser.HeadPicture;
                row["Sex"] = wxUser.Sex;
                row["IsSubscribe"] = wxUser.IsSubscribe;
                row["Subscribe_Date"] = wxUser.Subscribe_Date;
                row["City"] = wxUser.City;
                row["Province"] = wxUser.Province;
                row["Country"] = wxUser.Country;
                table.Rows.Add(row);                
            }

            using (SqlConnection connection = SqlHelper.CreateConn())
            {
                try
                {
                    connection.Open();
                    using (SqlBulkCopy sbc = new SqlBulkCopy(SqlHelper.CreateConn().ConnectionString, SqlBulkCopyOptions.UseInternalTransaction))
                    {
                        //服务器上目标表的名称   
                        sbc.DestinationTableName = table.TableName;
                        sbc.BatchSize = batchSize;
                        sbc.BulkCopyTimeout = 600;

                        for (int i = 0, l = table.Columns.Count; i < l; i++)
                        {
                            //列映射定义数据源中的列和目标表中的列之间的关系   
                            sbc.ColumnMappings.Add(table.Columns[i].ColumnName, table.Columns[i].ColumnName);
                        }

                        sbc.WriteToServer(table);
                    }
                }
                catch (Exception exp)
                {
                    throw exp;
                }
                finally
                {
                    connection.Close();
                }
            }

          
        }



       
    }
}
